#!/usr/bin/env python3
"""
启动摄像头监控系统
直接使用电脑摄像头进行AI监控
"""

import subprocess
import sys
import os
import time
import signal
import threading
from pathlib import Path

class CameraMonitoringSystem:
    def __init__(self):
        self.processes = []
        self.running = True
        
    def check_camera_availability(self):
        """检查摄像头是否可用"""
        try:
            import cv2
            cap = cv2.VideoCapture(0)  # 尝试打开默认摄像头
            if cap.isOpened():
                ret, frame = cap.read()
                cap.release()
                if ret:
                    print("✅ 摄像头检测成功")
                    return True
                else:
                    print("❌ 摄像头无法读取画面")
                    return False
            else:
                print("❌ 无法打开摄像头")
                return False
        except ImportError:
            print("❌ 缺少OpenCV库，请安装: pip install opencv-python")
            return False
        except Exception as e:
            print(f"❌ 摄像头检测失败: {e}")
            return False
    
    def start_django(self):
        """启动Django服务器"""
        print("🚀 启动Django社区管理系统...")
        django_dir = Path(__file__).parent / "Python" / "community_system"
        
        try:
            process = subprocess.Popen(
                [sys.executable, "manage.py", "runserver", "8000"],
                cwd=django_dir,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            self.processes.append(("Django", process))
            print("✅ Django服务器已启动: http://127.0.0.1:8000")
            return process
        except Exception as e:
            print(f"❌ Django启动失败: {e}")
            return None
    
    def start_ai_camera_system(self):
        """启动AI摄像头监控系统"""
        print("📹 启动AI摄像头监控系统...")
        ai_dir = Path(__file__).parent / "Python" / "aiWatchdog-main"
        
        try:
            # 修改配置文件使用摄像头
            config_file = ai_dir / "config.py"
            with open(config_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 确保使用摄像头
            content = content.replace('VIDEO_SOURCE = "./测试视频/04.mp4"', 'VIDEO_SOURCE = 0  # 使用默认摄像头')
            content = content.replace('VIDEO_SOURCE = 0  # 使用默认摄像头', 'VIDEO_SOURCE = 0  # 使用默认摄像头')
            
            with open(config_file, 'w', encoding='utf-8') as f:
                f.write(content)
            
            process = subprocess.Popen(
                [sys.executable, "video_server.py"],
                cwd=ai_dir,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            self.processes.append(("AI摄像头监控", process))
            print("✅ AI摄像头监控系统已启动: http://127.0.0.1:8001")
            return process
        except Exception as e:
            print(f"❌ AI摄像头监控系统启动失败: {e}")
            return None
    
    def monitor_process(self, name, process):
        """监控进程输出"""
        while self.running and process.poll() is None:
            try:
                output = process.stdout.readline()
                if output:
                    print(f"[{name}] {output.strip()}")
            except:
                break
    
    def start(self):
        """启动摄像头监控系统"""
        print("=" * 60)
        print("📹 AI摄像头监控系统 - 启动")
        print("=" * 60)
        
        # 检查摄像头
        if not self.check_camera_availability():
            print("❌ 摄像头不可用，请检查摄像头连接")
            return
        
        # 启动Django
        django_process = self.start_django()
        if not django_process:
            print("❌ 无法启动Django系统")
            return
        
        # 等待Django启动
        time.sleep(3)
        
        # 启动AI摄像头监控系统
        ai_process = self.start_ai_camera_system()
        if not ai_process:
            print("❌ 无法启动AI摄像头监控系统")
            return
        
        # 启动监控线程
        if django_process:
            threading.Thread(target=self.monitor_process, args=("Django", django_process), daemon=True).start()
        
        if ai_process:
            threading.Thread(target=self.monitor_process, args=("AI摄像头监控", ai_process), daemon=True).start()
        
        print("\n" + "=" * 60)
        print("🎉 摄像头监控系统启动完成！")
        print("📱 Django社区管理系统: http://127.0.0.1:8000")
        print("📹 AI摄像头监控系统: http://127.0.0.1:8001")
        print("📊 监控仪表板: http://127.0.0.1:8000/monitoring/")
        print("⚠️ 异常记录: http://127.0.0.1:8000/abnormal-records/")
        print("=" * 60)
        print("📹 摄像头正在实时监控中...")
        print("按 Ctrl+C 停止所有服务")
        print("=" * 60)
        
        try:
            # 等待进程结束
            while self.running:
                time.sleep(1)
                # 检查进程是否还在运行
                for name, process in self.processes:
                    if process.poll() is not None:
                        print(f"⚠️ {name} 进程意外退出")
                        self.running = False
                        break
        except KeyboardInterrupt:
            print("\n🛑 正在停止摄像头监控系统...")
            self.stop()
    
    def stop(self):
        """停止所有服务"""
        self.running = False
        for name, process in self.processes:
            try:
                print(f"🛑 停止 {name} 服务...")
                process.terminate()
                process.wait(timeout=5)
                print(f"✅ {name} 服务已停止")
            except:
                print(f"⚠️ 强制停止 {name} 服务...")
                process.kill()
        print("🎯 摄像头监控系统已停止")

def signal_handler(sig, frame):
    """信号处理器"""
    print("\n🛑 接收到停止信号...")
    sys.exit(0)

if __name__ == "__main__":
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # 启动摄像头监控系统
    system = CameraMonitoringSystem()
    try:
        system.start()
    except KeyboardInterrupt:
        system.stop()
    except Exception as e:
        print(f"❌ 系统启动失败: {e}")
        system.stop()

